package com.tth.learn.addproperties.java;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/**
 * @Author tth
 * @Date 2022/12/13 16:37
 */
public class TreeSetTest {

    @Test
    public void test1() {
        TreeSet treeSet = new TreeSet();
        treeSet.add(new User("Jack", 12));
        treeSet.add(new User("Janny", 22));
        treeSet.add(new User("Jery", 23));
        treeSet.add(new User("Jey", 34));
        treeSet.add(new User("Jane", 10));

        Iterator iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    @Test
    public void test2() {
        Comparator comparator = new Comparator() {
            // 按照年龄由大到小排序
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User) {
                    User user1 = (User) o1;
                    User user2 = (User) o2;
                    return -Integer.compare(user1.getAge(), user2.getAge());
                }

                throw new RuntimeException("输入的数据不匹配");
            }
        };

        TreeSet treeSet = new TreeSet(comparator);
        treeSet.add(new User("Jack", 12));
        treeSet.add(new User("Janny", 22));
        treeSet.add(new User("Jery", 23));
        treeSet.add(new User("Jey", 34));
        treeSet.add(new User("Jane", 10));

        Iterator iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }



    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
